﻿using ACC.Business;
using ACC.Business.Process;
using ACC.Business.Stn;
using ACC.Data;
using ACC.Data.ACCLog;
using ACC.Data.Comm;
using ACC.Data.Entities.Mes;
using ACC.Data.Line;
using ACC.Device;
using ACC.Device.PLC.Siemens;
using ACC.LineDevice.KukaPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace Script
{
    /// <summary>
    /// 绝缘板上料 
    /// OP L1M02020 STATION L1M12021, L1M22021
    /// </summary>
    public class L1M02020 : StnProcessPL02_JT
    {
        public L1M02020(StnRunningData data)
            : base(data)
        {
            IsReport = false;
            IsACCReport = false;
            IsPalletRelationSN = false;
        }

        protected override void CreateBusinessLogic()
        {
            base.CreateBusinessLogic();
            _loadProcess = new LoadProcess_Ex02020(_data);
            _unloadProcess = new UnloadProcess_Ex02020(_data);
        }

        protected override ACCDevice CreateDevice()
        {
            ACCDevice dev = base.CreateDevice();
            if (kukaSiemensDev != null)
            {
                kukaSiemensDev.DB190 = 800;
                kukaSiemensDev.DB190_Offset = 0;
                kukaSiemensDev.DB192 = 80;
                kukaSiemensDev.DB192_PLC_Offset = 290;
                kukaSiemensDev.DB193 = 800;
                kukaSiemensDev.DB193_PLC_Offset = 34;
                kukaSiemensDev.DB193_ACC_Offset = 68;
                kukaSiemensDev.DB194 = 800;
                kukaSiemensDev.DB194_PLC_Offset = 34;
                kukaSiemensDev.DB194_PLC_Data_Offset = 302;

                kukaSiemensDev.BarcodeLength = 30;
                kukaSiemensDev.LoadBarcodeCount = 2;
                kukaSiemensDev.UnloadBarcodeCount = 2;

                kukaSiemensDev.Material_COMM_Offset = 292;       // 上下料信号位偏移量
            }

            return dev;

        }
        public override ACCCode ReadLoadParam(ACCDevice dev, out ACCDevice.LoadParam param)
        {

            _data.ProcessUnitIDWhenLoad = true;
            ACCCode rs = base.ReadLoadParam(dev, out param);
            if (rs == ACCCode.ACCOK)
            {
                _data.Variables["firstBarcode"] = CreateVirtualBarcode();//第一个绝缘板条码
                _data.Variables["secondBarcode"] = CreateVirtualBarcode();//第二个绝缘板条码

                param.UnitSN = _data.Variables["firstBarcode"].ToString();
                param.PartTypeID = _data.PartNo == null ? 0 : (int)_data.PartNo.BomCfg.PartTypeID;
                param.PartNo = _data.PartNo;
                param.ComponentSN = new String[] { _data.Variables["secondBarcode"].ToString() };
            }

            return rs;
        }

        /// <summary>
        ///创建绝缘板的虚拟条码
        /// </summary>
        /// <returns></returns>
        public string CreateVirtualBarcode()
        {
            logger.Debug("Begin Create JY Barcode");
            string barcode = PartTypeTagProcess.GetPartTypeTagValue(_data.PartNo.BomCfg, "JYBarcode", logger);
            barcode = barcode.Replace("-", "");
            return barcode;
        }

        /// <summary>
        ///两个绝缘板LOADOK之后，一次性写入PLC指定地址块；
        /// </summary>
        /// <param name="dev"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public override ACCCode SendLoadResult(ACCDevice dev, ACCDevice.LoadResult result)
        {
            if (result.ErrorCode == ACCCode.ACCOK)
            {
                string fstBarcode = _data.Variables.ContainsKey("firstBarcode") ? _data.Variables["firstBarcode"].ToString() : string.Empty;
                string scdBarcode = _data.Variables.ContainsKey("secondBarcode") ? _data.Variables["secondBarcode"].ToString() : string.Empty;


                //将两个绝缘板条码一起写入PLC,由PLC记录在RFID
                if (!string.IsNullOrEmpty(fstBarcode) && !string.IsNullOrEmpty(scdBarcode))

                    SendBarcodeToPlc(new string[] { fstBarcode, scdBarcode }, kukaSiemensDev.DB193_PLC_Offset, 30);
            }
            return base.SendLoadResult(dev, result);
        }
    }

    /// <summary>
    /// 重写LoadProcess，一次load请求，进行两个绝缘板的进站操作
    /// </summary>
    public class LoadProcess_Ex02020 : LoadProcess
    {
        public LoadProcess_Ex02020(StnRunningData data)
            : base(data)
        {

        }

        public override void ProcessLoad(ACCDevice dev)
        {
            var barcodes = new string[] { _loadParam.UnitSN };
            var v = barcodes.Concat(_loadParam.ComponentSN);
            _loadParam.ComponentSN = new String[] { };
            foreach (string unitsn in v)
            {
                _loadParam.UnitSN = unitsn;

                base.ProcessLoad(dev);
                if (_loadResult.ErrorCode == ACCCode.ACCOK)
                    (_stnProcess as StnProcessKukaPack).ReportIn(dev, _data, _loadResult);
                else
                    return;
            }
        }
        /// 绝缘板条码进行了拆分处理
        /// </summary>
        /// <param name="loadSNs"></param>
        /// <param name="CompCfg"></param>
        /// <param name="param"></param>
        /// <param name="result"></param>
        protected override void CheckComponentCount(List<string> loadSNs, BomItemCfg[] CompCfg, ACCDevice.LoadParam param, ref ACCDevice.LoadResult result)
        {
            //base.CheckComponentCount(loadSNs, CompCfg, param, ref result);
            int compCount = (int)CompCfg.Sum(c => c.QtyPer <= 0 ? 1 : c.QtyPer);
            if (loadSNs.Count < 1)
            {
                result.ErrorCode = ACCCode.Load_Mismatch_ComponentPattern;
                throw new ACCException(ErrorConstants.LOAD_COMPONET_COUNT_NOTMATCH, loadSNs.Count, compCount);
            }
        }
    }

    /// <summary>
    /// 出站时，PLC将两个绝缘板条码一起传上来
    /// 对两个绝缘板进行UNLOAD进行拆分处理
    /// </summary>
    public class UnloadProcess_Ex02020 : UnloadProcess
    {
        public UnloadProcess_Ex02020(StnRunningData data)
            : base(data)
        {

        }

        public override void ProcessUnload(ACCDevice dev)
        {
            var barcodes = new string[] { _unloadParam.UnitSN };
            var v = barcodes.Concat(_unloadParam.ComponentSN);
            _unloadParam.ComponentSN = new String[] { };
            foreach (string unitsn in v)
            {
                _unloadParam.UnitSN = unitsn;

                base.ProcessUnload(dev);
                if (_unloadResult.ErrorCode == ACCCode.ACCOK)
                    (_stnProcess as StnProcessKukaPack).ReportOut(dev, _data, _unloadParam, _unloadResult);
                else
                    return;
            }
        }

        /// <summary>
        /// 绝缘板条码进行了拆分处理
        /// </summary>
        /// <param name="loadSNs"></param>
        /// <param name="CompCfg"></param>
        /// <param name="param"></param>
        /// <param name="result"></param>
        protected override void CheckComponentCount(List<string> loadSNs, BomItemCfg[] CompCfg, ACCDevice.UnloadParam param, ref ACCDevice.UnloadResult result)
        {
            //base.CheckComponentCount(loadSNs, CompCfg, param, ref result);
            int compCount = (int)CompCfg.Sum(c => c.QtyPer <= 0 ? 1 : c.QtyPer);
            if (loadSNs.Count < 1)
            {
                result.ErrorCode = ACCCode.Load_Mismatch_ComponentPattern;
                throw new ACCException(ErrorConstants.LOAD_COMPONET_COUNT_NOTMATCH, loadSNs.Count, compCount);
            }
        }
    }
}